﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using UserData;
using Communicate;
using CommonTools;
using CommonDlg;
namespace StationDemo
{
    public class LoadServer
    {
        
        bool b_HeartRecive = false;
        bool b_HeartFlag = false;
        Thread thread_HeartMonitor;
        public  string name = "";
        public LoadServer(string Name)
        {
            name = Name;
        }
            

        SocketSever socketSever = new SocketSever();
        public void Run(string ip, int port)
        {
            socketSever.Init(ip, port,"TCP");
            socketSever.ProcessData += ProcessData;
            thread_HeartMonitor = new Thread(HeartMonitor);
            thread_HeartMonitor.IsBackground = true;
            thread_HeartMonitor.Start();
        }
        private void HeartMonitor()
        {
            while (true)
            {
                Thread.Sleep(5000);
                b_HeartFlag = b_HeartRecive;
                b_HeartRecive = false;
            }
        }

        private List<string> m_Start = new List<string>();
        private List<string> m_TestCmd = new List<string>();
        private List<string> m_MesCmd = new List<string>();
        private List<string> m_StopCmd = new List<string>();

        string ReceiveAllString = "";
        private void ProcessData( string data)
        {
            try
            {
                ReceiveAllString = ReceiveAllString + data;
                if (!ReceiveAllString.Contains("*"))
                    return;
                string str_Restle = ReceiveAllString.Replace("\r\n", "*");
                string[] s_Restle = str_Restle.Split('*');
                for (int i = 0; i < s_Restle.Length; i++)
                {
                    if (s_Restle[i] == "")
                        continue;
                    if (s_Restle[i].Contains("Heart"))
                    {
                        Send("HeartOK");
                        b_HeartRecive = true;
                    }
                    else
                    {
                        LogHelper.OnTest_ShowLog("Server", $"{name}接收消息:{s_Restle[i]}", LogType.Warn);
                        if (s_Restle[i].Contains("StartFail") || s_Restle[i].Contains("StartOK"))
                        {
                            m_Start.Add(s_Restle[i]);
                        }
                        else if (s_Restle[i].Contains("TestOK") || s_Restle[i].Contains("TestFail"))
                        {
                            m_TestCmd.Add(s_Restle[i]);
                        }
                        else if (s_Restle[i].Contains("MesOK") || s_Restle[i].Contains("MesFail"))
                        {
                            m_MesCmd.Add(s_Restle[i]);
                        }
                        else if (s_Restle[i].Contains("StopOK") || s_Restle[i].Contains("StopFail"))
                        {
                            m_StopCmd.Add(s_Restle[i]);
                        }

                    }

                }
                ReceiveAllString = s_Restle[s_Restle.Length - 1];
              

            }
            catch (Exception ex)
            {

            }

        }
        object obj = new object();
        private void Send(string SendStr)
        {
            lock (obj)
            {
                try
                {
                    Thread.Sleep(100);
                    if (!SendStr.Contains("Heart"))
                    {
                        LogHelper.OnTest_ShowLog("Server", $"{name}发送:{SendStr}");
                    }

                    socketSever.Send(SendStr);
                }
                catch (Exception ex)
                {
                   LogHelper.OnTest_ShowLog(name, $"{name}发送消息异常{ex.Message}{ex.StackTrace}",LogType.Err);
                }
             
            }
            
        }
        public bool Function_IsConnect()
        {
            return b_HeartFlag;
        }
        public int Cmd_运控平台通知标定平台启动(int Timeout = 10000)
        {
            try
            {
                if (!Function_IsConnect())
                {
                    MessageBox.Show($"{name}未连接");
                    return -1;
                }
                m_Start.Clear();
                Send($"StartCmd:0*");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > Timeout)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (m_Start.Count != 0)
                    {
                        str_Recive = m_Start[0];
                        break;
                    }
                }
                return str_Recive== "StartOK"?0:-1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }
        public int Cmd_运控平台通知标定平台测试(string cmd, int Timeout = 10000)
        {
            try
            {
                if (!Function_IsConnect())
                {
                    MessageBox.Show($"{name}未连接");
                    return -1;
                }
                m_TestCmd.Clear();
                Send($"TestCmd:{cmd}*");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > Timeout)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (m_TestCmd.Count != 0)
                    {
                        str_Recive = m_TestCmd[0];
                        break;
                    }
                }
                return str_Recive.Contains("TestOK") ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }

        public int Cmd_运控平台通知标定平台测试并返回结果(string cmd, ref string result, int Timeout = 10000)
        {
            try
            {
                if (!Function_IsConnect())
                {
                    MessageBox.Show($"{name}未连接");
                    return -1;
                }
                m_TestCmd.Clear();
                Send($"TestCmd:{cmd}*");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > Timeout)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (m_TestCmd.Count != 0)
                    {
                        str_Recive = m_TestCmd[0];
                        string[] str = str_Recive.Split(':');
                        result = str[1];
                        break;
                    }
                }
                return str_Recive.Contains("TestOK") ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }
        public int Cmd_运控平台通知三角平台测试并返回结果(string cmd, ref string result, int Timeout = 10000)
        {
            try
            {
                if (!Function_IsConnect())
                {
                    MessageBox.Show($"{name}未连接");
                    return -1;
                }
                m_MesCmd.Clear();
                Send($"MesCmd:{cmd}*");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > Timeout)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (m_MesCmd.Count != 0)
                    {
                        str_Recive = m_MesCmd[0];
                        string[] str = str_Recive.Split(':');
                        result = str[1];
                        break;
                    }
                }
                return str_Recive.Contains("MesOK") ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }
        public int Cmd_运控平台通知标定平台停止(int Timeout = 10000)
        {
            try
            {
                if (!Function_IsConnect())
                {
                    MessageBox.Show($"{name}未连接");
                    return -1;
                }
                m_StopCmd.Clear();
                Send("StopCmd*");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > Timeout)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (m_StopCmd.Count != 0)
                    {
                        str_Recive = m_StopCmd[0];
                        break;
                    }
                }
                return str_Recive == "StopOK" ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }

    }
}